﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CipherBox
{
    public delegate void SaveKeyPath(string path);
    public delegate void SaveRemotePath(string path);
    public partial class SettingsDialog : Form
    {
        public SettingsDialog()
        {
            InitializeComponent();

        }
        string SETTINGS_PATH = Application.StartupPath + "\\settings.xml";
        private void FormSettings_Load(object sender, EventArgs e)
        {
            try
            {
                m_Settings = XMLSerializing.Deserialize<settings>(SETTINGS_PATH);
                foreach (settingsJob j in m_Settings.job)
                {
                    AddListViewItem(j.email, j.token, j.localPath, j.remotePath, j.key, j.incomingSync ? "X" : string.Empty, j.outgoingSync ? "X" : string.Empty);
                }
            }
            catch (FileNotFoundException)
            {
                m_Settings = new settings();
            }
            textBoxInterval.Text = m_Settings.SynchronisationInterval.ToString();
            checkBoxSplash.Checked = m_Settings.showSplash;
        }
        settings m_Settings = new settings();
        DropBox m_DropBox;
        DropBox dropBox
        {
            get
            {
                try
                {
                    if (m_DropBox == null)
                    {
                        m_DropBox = new DropBox(textBoxEmail.Text, textBoxPass.Text);
                    }
                    return m_DropBox;
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show("Autorization failed. wrong login?");
                    throw new UnauthorizedAccessException(ex.Message);
                }

            }
        }


        private void listBoxJobs_DoubleClick(object sender, EventArgs e)
        {
            dropBox.Browse(listViewJobs.Items[listViewJobs.SelectedIndices[0]].Text);
        }


        private void listViewJobs_SelectedIndexChanged(object sender, EventArgs e)
        {
            buttonRemove.Enabled = true;
            buttonEdit.Enabled = true;
        }


        private void AddListViewItem(params string[] fields)
        {
            ListViewItem lineitem = new ListViewItem(fields[0]);
            for (int i = 1; i < fields.Length; i++)
            {
                lineitem.SubItems.Add(fields[i]);
            }
            listViewJobs.Items.Add(lineitem);
        }
        private void SetDetails()
        {
            if (listViewJobs.SelectedIndices.Count == 0)
            {
                MessageBox.Show("Please select a job!");
                return;
            }
            settingsJob j = m_Settings.job[listViewJobs.SelectedIndices[0]];
            textBoxEmail.Text = j.email;
            textBoxKey.Text = j.key;
            textBoxLocalPath.Text = j.localPath;
            textBoxRemotePath.Text = j.remotePath;
            checkBoxIncoming.Checked = j.incomingSync;
            checkBoxOutgoing.Checked = j.outgoingSync;
        }
        private void ClearDetails()
        {
            textBoxEmail.Text = string.Empty;
            textBoxKey.Text = string.Empty;
            textBoxLocalPath.Text = string.Empty;
            textBoxPass.Text = string.Empty;
            checkBoxIncoming.Checked = false;
            checkBoxOutgoing.Checked = false;
        }


        private void buttonRemote_Click_1(object sender, EventArgs e)
        {
            try
            {
                SaveRemotePath del = delegate(string path) { textBoxRemotePath.Text = path; };
                SelectFolderDialog c = new SelectFolderDialog(dropBox, del);
                c.ShowDialog(this);

            }
            catch (UnauthorizedAccessException) { }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (textBoxRemotePath.Text != string.Empty&&(checkBoxIncoming.Checked||checkBoxOutgoing.Checked))
            {
                buttonAdd.Enabled = true;
            }
            else
            {
                buttonAdd.Enabled = false;
            }
            if (textBoxEmail.Text == string.Empty || textBoxPass.Text == string.Empty)
            {
                buttonKey.Enabled = false;
                buttonLocal.Enabled = false;
                buttonRemote.Enabled = false;
            }
            else
            {
                buttonKey.Enabled = true;
                buttonLocal.Enabled = true;
                buttonRemote.Enabled = true;
            }
            if (listViewJobs.SelectedIndices.Count == 0)
            {
                buttonEdit.Enabled = false;
                buttonRemove.Enabled = false;
            }
            else
            {
                buttonEdit.Enabled = true;
                buttonRemove.Enabled = true;
            }
        }

        private void buttonAdd_Click_1(object sender, EventArgs e)
        {
            try
            {

                string tokenPath = Application.StartupPath + "\\" + textBoxEmail.Text + ".AccessToken";
                dropBox.SaveToken(tokenPath);
                AddListViewItem(textBoxEmail.Text, tokenPath, textBoxLocalPath.Text, textBoxRemotePath.Text, textBoxKey.Text, checkBoxIncoming.Checked ? "X" : string.Empty, checkBoxOutgoing.Checked ? "X" : string.Empty);
                m_Settings.job.Add(new settingsJob() { email = textBoxEmail.Text, key = textBoxKey.Text, localPath = textBoxLocalPath.Text, name = "Job" + listViewJobs.Items.Count.ToString(), remotePath = textBoxRemotePath.Text, token = tokenPath, outgoingSync = checkBoxOutgoing.Checked, incomingSync = checkBoxIncoming.Checked });
                ClearDetails();

            }
            catch (UnauthorizedAccessException) { }
        }

        private void buttonEdit_Click_1(object sender, EventArgs e)
        {
            if (listViewJobs.SelectedIndices.Count == 0)
            {
                MessageBox.Show("Please select a job!");
                return;
            }
            buttonRemove.Enabled = false;
            buttonEdit.Enabled = false;
            SetDetails();

            m_Settings.job.RemoveAt(listViewJobs.SelectedIndices[0]);
            listViewJobs.Items.RemoveAt(listViewJobs.SelectedIndices[0]);
        }
        int Interval = 60;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            int d;
            if (int.TryParse(textBoxInterval.Text,out d))
            {
                Interval = d;
                m_Settings.SynchronisationInterval = d;
            }
            else
            {
                textBoxInterval.Text = Interval.ToString();
            }
        }


        private void buttonRemove_Click_1(object sender, EventArgs e)
        {
            buttonRemove.Enabled = false;
            buttonEdit.Enabled = false;
            listViewJobs.Items.RemoveAt(listViewJobs.SelectedIndices[0]);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XMLSerializing.Serialize<settings>(SETTINGS_PATH, m_Settings);
            this.Close();
        }

        private void buttonLocal_Click_1(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            if (folderBrowserDialog1.SelectedPath != string.Empty)
            {
                textBoxLocalPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void buttonKey_Click_1(object sender, EventArgs e)
        {
           DialogResult r= MessageBox.Show("would you like to generate a keyfile?", "question", MessageBoxButtons.YesNo);
           if (r.ToString() == "Yes")
           {
               SaveKeyPath callback = delegate(string path) { textBoxKey.Text = path; };
               KeyGeneratorDialog d = new KeyGeneratorDialog(callback);
               d.ShowDialog();
           }
           else
           {
               openFileDialog1.ShowDialog();
               if (openFileDialog1.FileName != string.Empty)
               {
                   textBoxKey.Text = openFileDialog1.FileName;
               }
           }
        }

    }
}
